import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    // 1.仓库数据
    count: 0,
    address: '成都市武侯区科华北路力宝大厦',
    list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  },
  getters: {
    arr (state) {
      return state.list.filter(value => value > 5)
    },
    arr2 (state) {
      return state.list.filter(value => value < 5)
    }
  },
  mutations: {
    // 2.修改仓库数据的唯一途径(mutations)
    // 注意：这里只能写同步代码，不能写异步代码（setTimeout,setInterval,Promise,Ajax,axios）
    increment (state, obj) {
      state.count += obj.num
    },
    decrement (state, obj) {
      state.count -= obj.num
    }
  },
  actions: {
    sub (context, obj) {
      setTimeout(() => {
        context.commit('decrement', obj)
      }, 2000)
    },
    testPromise () {
      return new Promise((resolve, reject) => {
        resolve('Hello Vue.js')
      })
    },
    testPromise2 ({dispatch, commit}) {
      dispatch('testPromise').then((res) => {
        console.log(res)
      })
    }
  }
})

export default store
